#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <string>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "log.hpp"
#include "InetAddr.hpp"

enum
{
    sockect_create_error = 1,
    bind_error,
    usage_error,
};

class UdpServer
{
public:
    UdpServer(/*std::string &ip,*/ uint16_t port)
        : _socketfd(-1), /*_ip(ip), */ _port(port)
    {
    }
    void init()
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketfd < 0)
        {
            Log(FATAL, "sockect create error:%s", strerror(errno));
            exit(sockect_create_error);
        }
        Log(INFO, "socket create success");
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_addr.s_addr = INADDR_ANY;
        int ret = bind(_socketfd, (const sockaddr *)&local, sizeof(local));
        if (ret < 0)
        {
            Log(FATAL, "bind false:%s", strerror(errno));
            exit(bind_error);
        }
        Log(INFO, "bind success");
    }
    void start()
    {
        while (true)
        {
            char buffer[1024];
            //bzero(buffer,sizeof(buffer));
            struct sockaddr_in src_addr;
            socklen_t addrlen = sizeof(src_addr);
            // 收消息
            //std::cout<<"收到前buffer:"<<buffer<<std::endl;
            ssize_t n = recvfrom(_socketfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&src_addr, &addrlen);
            //std::cout<<"收到后buffer:"<<buffer<<std::endl;
            if (n > 0)
            {
                InetAddr addr(src_addr);
                Log(DEBUG, "get message from[%s:%d]:%s", addr.ip(), addr.port(), buffer);
                // 发消息
                sendto(_socketfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&src_addr, addrlen);
            }
        }
    }

private:
    int _socketfd;
    // std::string _ip; 不建议绑定固定ip
    uint16_t _port;
};
